<template>
  <div class="question-card" :class="cardClass" @click="handleCardClick">
    <!-- 题目头部 -->
    <div class="question-header">
      <!-- 题目类型和难度 -->
      <div class="question-meta">
        <el-tag :type="getQuestionTypeTag()" size="small">{{ getQuestionTypeText() }}</el-tag>
        <el-tag :type="getDifficultyTag()" size="small">{{ getDifficultyText() }}</el-tag>
      </div>
      
      <!-- 操作按钮 -->
      <div v-if="showActions" class="question-actions">
        <button
          v-if="canEdit"
          class="action-btn action-edit"
          @click.stop="handleEdit"
          title="编辑"
        >
          <el-icon><Edit /></el-icon>
        </button>
        <button
          v-if="canDelete"
          class="action-btn action-delete"
          @click.stop="handleDelete"
          title="删除"
        >
          <el-icon><Delete /></el-icon>
        </button>
        <button
          v-if="canFavorite && !isFavorite"
          class="action-btn action-favorite"
          @click.stop="handleFavorite"
          title="收藏"
        >
          <el-icon><Star /></el-icon>
        </button>
        <button
          v-if="canFavorite && isFavorite"
          class="action-btn action-favorite active"
          @click.stop="handleUnfavorite"
          title="取消收藏"
        >
          <el-icon><StarFilled /></el-icon>
        </button>
        <button
          class="action-btn action-more"
          @click.stop="handleMore"
          title="更多"
        >
          <el-icon><More /></el-icon>
        </button>
      </div>
    </div>
    
    <!-- 题目内容 -->
    <div class="question-content">
      <!-- 分类标签 -->
      <div v-if="question.category" class="question-category">
        <el-tag type="info" size="small">{{ question.category.name }}</el-tag>
      </div>
      
      <!-- 题目文本 -->
      <div class="question-text" v-html="question.text || ''"></div>
      
      <!-- 选项 -->
      <div v-if="question.options && question.options.length > 0" class="question-options">
        <div
          v-for="(option, index) in question.options"
          :key="index"
          :class="['option-item', {
            'selected': userAnswer === index,
            'correct': showAnswer && option.isCorrect,
            'incorrect': showAnswer && userAnswer === index && !option.isCorrect
          }]"
          @click="handleOptionClick(index)"
        >
          <span class="option-label">{{ getOptionLabel(index) }}</span>
          <span class="option-text" v-html="option.text"></span>
          <span v-if="showAnswer" class="option-status">
            <el-icon v-if="option.isCorrect"><Check /></el-icon>
            <el-icon v-else-if="userAnswer === index"><Close /></el-icon>
          </span>
        </div>
      </div>
      
      <!-- 答案解析 -->
      <div v-if="showAnswer && question.explanation" class="question-explanation">
        <h4 class="explanation-title">答案解析</h4>
        <div class="explanation-content" v-html="question.explanation"></div>
      </div>
      
      <!-- 自定义内容 -->
      <div v-if="$slots.content" class="question-custom-content">
        <slot name="content" :question="question" />
      </div>
    </div>
    
    <!-- 题目统计 -->
    <div v-if="showStats && question.stats" class="question-stats">
      <div class="stat-item">
        <span class="stat-label">正确率</span>
        <span class="stat-value">{{ question.stats.correctRate || 0 }}%</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">练习次数</span>
        <span class="stat-value">{{ question.stats.practiceCount || 0 }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">收藏次数</span>
        <span class="stat-value">{{ question.stats.favoriteCount || 0 }}</span>
      </div>
    </div>
    
    <!-- 底部操作 -->
    <div v-if="showBottomActions" class="question-bottom-actions">
      <button
        v-if="!showAnswer"
        class="action-btn action-submit"
        @click.stop="handleSubmit"
        :disabled="userAnswer === null"
      >
        提交答案
      </button>
      <button
        v-if="showAnswer"
        class="action-btn action-next"
        @click.stop="handleNext"
      >
        下一题
      </button>
      <button class="action-btn action-report" @click.stop="handleReport">
        报错
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, withDefaults, defineProps, defineEmits } from 'vue'
import { useRouter } from 'vue-router'
import type { Question, QuestionCategory, QuestionOption } from '../types/question'
import { ElTag, ElIcon } from 'element-plus'
import {
  Edit,
  Delete,
  Star,
  StarFilled,
  More,
  Check,
  Close
} from '@element-plus/icons-vue'

// 扩展Question接口添加缺失的属性
interface ExtendedQuestion extends Question {
  text?: string
  explanation?: string
  // 重新定义options属性，允许content或text属性
  options?: Array<QuestionOption & { text?: string }>
  stats?: {
    correctRate?: number
    practiceCount?: number
    favoriteCount?: number
  }
}

// Props
interface Props {
  question: Partial<ExtendedQuestion & { category?: Partial<QuestionCategory> }>
  currentUserId?: string | number
  isAdmin?: boolean
  isModerator?: boolean
  isFavorite?: boolean
  showAnswer?: boolean
  showStats?: boolean
  showActions?: boolean
  showBottomActions?: boolean
  canEdit?: boolean
  canDelete?: boolean
  canFavorite?: boolean
  size?: 'small' | 'medium' | 'large'
  interactive?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  question: () => ({}),
  isAdmin: false,
  isModerator: false,
  isFavorite: false,
  showAnswer: false,
  showStats: true,
  showActions: true,
  showBottomActions: true,
  canEdit: false,
  canDelete: false,
  canFavorite: true,
  size: 'medium',
  interactive: true
})

// Router
const router = useRouter()

// Emits
const emit = defineEmits<{
  'edit': [question: Partial<Question>]
  'delete': [question: Partial<Question>]
  'favorite': [question: Partial<Question>]
  'unfavorite': [question: Partial<Question>]
  'submit': [question: Partial<Question>, answer: number | null]
  'next': [question: Partial<Question>]
  'report': [question: Partial<Question>]
  'more': [question: Partial<Question>]
}>()

// Refs
const userAnswer = ref<number | null>(null)
const internalIsFavorite = ref(props.isFavorite)

// 计算属性
const cardClass = computed(() => {
  return [
    `question-card-${props.size}`,
    {
      'question-card-interactive': props.interactive,
      'question-card-answered': props.showAnswer
    }
  ]
})

// 获取题目类型文本
const getQuestionTypeText = () => {
  const typeMap: Record<string, string> = {
    'single': '单选题',
    'multiple': '多选题',
    'judgment': '判断题',
    'blank': '填空题',
    'essay': '简答题'
  }
  return typeMap[props.question.type as string] || '未知题型'
}

// 获取题目类型标签样式
const getQuestionTypeTag = (): "primary" | "success" | "warning" | "info" | "danger" => {
  const typeMap: Record<string, "primary" | "success" | "warning" | "info" | "danger"> = {
    'single': 'primary',
    'multiple': 'success',
    'judgment': 'warning',
    'blank': 'info',
    'essay': 'info'
  }
  return typeMap[props.question.type as string] || 'info'
}

// 获取难度文本
const getDifficultyText = () => {
  const difficultyMap: Record<string, string> = {
    'easy': '简单',
    'medium': '中等',
    'hard': '困难'
  }
  return difficultyMap[props.question.difficulty as string] || '未知难度'
}

// 获取难度标签样式
const getDifficultyTag = (): "primary" | "success" | "warning" | "info" | "danger" => {
  const difficultyMap: Record<string, "primary" | "success" | "warning" | "info" | "danger"> = {
    'easy': 'success',
    'medium': 'warning',
    'hard': 'danger'
  }
  return difficultyMap[props.question.difficulty as string] || 'info'
}

// 获取选项标签
const getOptionLabel = (index: number) => {
  return String.fromCharCode(65 + index)
}

// 事件处理
const handleEdit = () => {
  emit('edit', props.question)
}

const handleDelete = () => {
  emit('delete', props.question)
}

const handleFavorite = () => {
  emit('favorite', props.question)
  internalIsFavorite.value = true
}

const handleUnfavorite = () => {
  emit('unfavorite', props.question)
  internalIsFavorite.value = false
}

const handleCardClick = () => {
  if (props.question.id) {
    // 跳转到题目详情页
    router.push(`/question-detail/${props.question.id}`)
  }
}

const handleOptionClick = (index: number) => {
  if (props.interactive && !props.showAnswer) {
    userAnswer.value = index
  }
}

const handleSubmit = () => {
  emit('submit', props.question, userAnswer.value)
}

const handleNext = () => {
  emit('next', props.question)
}

const handleReport = () => {
  emit('report', props.question)
}

const handleMore = () => {
  emit('more', props.question)
}

// 暴露方法
defineExpose({
  submit: handleSubmit,
  next: handleNext,
  toggleFavorite: () => {
    if (internalIsFavorite.value) {
      handleUnfavorite()
    } else {
      handleFavorite()
    }
  },
  resetAnswer: () => {
    userAnswer.value = null
  }
})
</script>

<style scoped>
.question-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

/* 尺寸样式 */
.question-card-small {
  padding: 12px;
}

.question-card-medium {
  padding: 16px;
}

.question-card-large {
  padding: 20px;
}

/* 交互样式 */
.question-card-interactive {
  cursor: default;
}

/* 题目头部 */
.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.question-meta {
  display: flex;
  gap: 8px;
}

/* 操作按钮 */
.question-actions {
  display: flex;
  gap: 4px;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  padding: 0;
  border: none;
  border-radius: 4px;
  background-color: transparent;
  color: #909399;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-btn:hover {
  background-color: #f0f2f5;
  color: #606266;
}

.action-btn.active {
  color: #f56c6c;
}

.action-edit:hover {
  color: #409eff;
}

.action-delete:hover {
  color: #f56c6c;
}

.action-favorite:hover,
.action-favorite.active {
  color: #f56c6c;
}

/* 题目内容 */
.question-content {
  margin-bottom: 16px;
}

.question-category {
  margin-bottom: 8px;
}

.question-text {
  font-size: 15px;
  line-height: 1.6;
  color: #303133;
  margin-bottom: 12px;
}

/* 选项 */
.question-options {
  margin-bottom: 16px;
}

.option-item {
  display: flex;
  align-items: flex-start;
  padding: 10px 12px;
  margin-bottom: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.option-item:hover:not(:disabled) {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.option-item.selected {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.option-item.correct {
  border-color: #67c23a;
  background-color: #f0f9eb;
}

.option-item.incorrect {
  border-color: #f56c6c;
  background-color: #fef0f0;
}

.option-label {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  margin-right: 8px;
  border-radius: 50%;
  background-color: #f5f7fa;
  color: #606266;
  font-size: 14px;
  font-weight: 500;
  flex-shrink: 0;
}

.option-item.selected .option-label {
  background-color: #409eff;
  color: white;
}

.option-item.correct .option-label {
  background-color: #67c23a;
  color: white;
}

.option-item.incorrect .option-label {
  background-color: #f56c6c;
  color: white;
}

.option-text {
  flex: 1;
  font-size: 14px;
  line-height: 1.5;
  color: #606266;
}

.option-status {
  display: flex;
  align-items: center;
  margin-left: 8px;
  color: #67c23a;
}

.option-item.incorrect .option-status {
  color: #f56c6c;
}

/* 答案解析 */
.question-explanation {
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.explanation-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.explanation-content {
  font-size: 14px;
  line-height: 1.6;
  color: #606266;
}

/* 题目统计 */
.question-stats {
  display: flex;
  justify-content: space-around;
  padding-top: 12px;
  border-top: 1px solid #f0f2f5;
  margin-bottom: 12px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  display: block;
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.stat-value {
  display: block;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

/* 底部操作 */
.question-bottom-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f2f5;
}

.question-bottom-actions .action-btn {
  width: auto;
  padding: 6px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
}

.action-submit {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.action-submit:hover:not(:disabled) {
  background-color: #66b1ff;
  border-color: #66b1ff;
  color: white;
}

.action-submit:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.action-next {
  background-color: #67c23a;
  color: white;
  border-color: #67c23a;
}

.action-next:hover {
  background-color: #85ce61;
  border-color: #85ce61;
  color: white;
}

.action-report {
  background-color: #fff;
  color: #606266;
  border-color: #dcdfe6;
}

.action-report:hover {
  color: #409eff;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .question-card {
    margin-bottom: 12px;
  }
  
  .question-card-small {
    padding: 10px;
  }
  
  .question-card-medium {
    padding: 14px;
  }
  
  .question-card-large {
    padding: 18px;
  }
  
  .question-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .question-actions {
    align-self: flex-end;
  }
  
  .question-text {
    font-size: 14px;
  }
  
  .option-item {
    padding: 8px 10px;
  }
  
  .option-text {
    font-size: 13px;
  }
  
  .question-stats {
    flex-wrap: wrap;
    gap: 12px;
  }
  
  .question-bottom-actions {
    flex-direction: column;
  }
  
  .question-bottom-actions .action-btn {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .option-label {
    width: 20px;
    height: 20px;
    font-size: 12px;
  }
  
  .explanation-content {
    font-size: 13px;
  }
}
</style>